/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.apkfuns.jsbridge.util;

import ohos.agp.utils.TextTool;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Base64;

/**
 * CameraUtil
 *
 * @since 2021-3-8
 */
public final class CameraUtil {
    /**
     * camera image file path
     */
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00218, "CameraUtil");
    /**
     * is camera rear
     */
    private static boolean isCameraRear = true;
    private static final String IMAGE_TYPE_PNG = "image/png";
    private CameraUtil(){

    }
    /**
     * Obtains the PixelMap of an image.
     *
     * @param imageBytes  Image byte stream
     * @param imagePath   Image path
     * @param rotateCount angle of rotation
     * @return PixelMap
     */
    public static PixelMap getPixelMap(byte[] imageBytes, String imagePath, int rotateCount) {
        ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
        sourceOptions.formatHint = IMAGE_TYPE_PNG;
        ImageSource imageSource = null;
        if (imagePath != null && !imagePath.isEmpty()) {
            imageSource = ImageSource.create(imagePath, sourceOptions);
        } else if (imageBytes != null) {
            imageSource = ImageSource.create(imageBytes, sourceOptions);
        } else {
            return null;
        }
        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.desiredSize = new Size(0, 0);
        decodingOpts.rotateDegrees = (isCameraRear ? 270 : 90) * rotateCount;
        decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;
        return imageSource.createPixelmap(decodingOpts);
    }

    public static PixelMap getPixelMapByStream(FileInputStream fileInputStream, int rotateCount) {
        ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
        sourceOptions.formatHint = IMAGE_TYPE_PNG;
        ImageSource imageSource = ImageSource.create(fileInputStream, sourceOptions);

        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.desiredSize = new Size(0, 0);
        decodingOpts.rotateDegrees = (isCameraRear ? 270 : 90) * rotateCount;
        decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;
        return imageSource.createPixelmap(decodingOpts);
    }

    public static PixelMap getPixelMapByPath(String path, int rotateCount)  {
        File myFile = new File(path);
        FileInputStream fileInputStream = null;
        PixelMap pixelMap = null;
        try {
            fileInputStream = new FileInputStream(myFile);

            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/jpg";
            ImageSource imageSource = ImageSource.create(fileInputStream, sourceOptions);


            ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
            //decodingOpts.desiredSize = new Size(720, 720);
            //decodingOpts.rotateDegrees = 90;//(isCameraRear ? 270 : 90) * rotateCount;
            decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;
            pixelMap = imageSource.createPixelmap(decodingOpts);
        } catch (FileNotFoundException e) {
            HiLog.error(LABEL, "FileNotFoundException " + e);
        } finally {
            if(fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    HiLog.error(LABEL, "IOException " + e);

                }
            }
        }

        return pixelMap;
    }

    public static String imageFileToBase64String(String imageFile){
        String imageString = null;

        if(TextTool.isNullOrEmpty(imageFile)){

            return null;
        }
        File file = new File(imageFile);

        HiLog.info(LABEL, "resultSet newFile " + file.getPath());
        if(file.exists() && file.isFile()){

            FileInputStream input = null;
            try {
                input = new FileInputStream(file);

                byte[] bytes  = new byte[input.available()];
                input.read(bytes);
                input.close();
                imageString =   Base64.getEncoder().encodeToString(bytes);
               // imageString = getBase64String(imageFile,imageString);
            } catch (FileNotFoundException e) {
                HiLog.error(LABEL, "FileNotFoundException " + e);
            } catch (IOException e) {
                HiLog.error(LABEL, "IOException " + e);
            } finally {
                if(input!=null){
                    try {
                        input.close();
                    } catch (IOException e) {

                        HiLog.error(LABEL, "IOException " + e);
                    }
                }
            }

        }

        return imageString;
    }


    public static String getBase64String(String fileName,String img) {
        if (fileName!=null) {//"data:image/png;base64," + base64;
            String base64 = "";
            if (fileName.endsWith("jpg")) {
                base64 += " data:image/jpg;base64,";
            } else if (fileName.endsWith("ico")) {
                base64 += " data:image/ico;base64,";
            } else if (fileName.endsWith("gif")) {
                base64 += " data:image/gif;base64,";
            } else if (fileName.endsWith("png")) {
                base64 += " data:image/png;base64,";
            }
            return base64 +img;
        }
        return null;
    }


}
